<template>
    <Rich-text-editor
        ref="editRef"
        v-model:modelValue="htmlStr"
        :mode="mode"
        :height="height"
        :width="width"
        :borderColor="borderColor"
        :maxImageSize="maxImageSize"
        :maxVideoSize="maxVideoSize"
        :placeholder="placeholder"
        :customUploadImage="handleUploadImage"
        :customUploadVideo="handleUploadVideo"
        @onDeletedResources="handleDeletedResources"
    />
</template>

<script setup lang="ts">
import type { IDomEditor } from "@wangeditor-next/editor";

import { useFileHash } from "@/hooks/useFileHash";

import RichTextEditor from "./RichTextEditor.vue";

defineProps<{
    modelValue: string;
    mode?: "default" | "simple"; // 编辑器模式，默认为完整功能
    height?: string | number;
    width?: string | number;
    borderColor?: string;
    placeholder?: string; // 编辑器占位文本
    maxImageSize?: number; // 图片最大上传大小（单位：MB），默认 5MB
    maxVideoSize?: number; // 视频最大上传大小（单位：MB），默认 100MB
}>();

const emit = defineEmits<{
    "update:modelValue": [value: string]; // v-model 更新事件
}>();

const editRef = ref<InstanceType<typeof RichTextEditor> | null>(null);
const htmlStr = ref("");

const { calculateFileHash } = useFileHash();

const handleUploadImage = async (
    file: File,
    insertFn: (url: string, alt: string, href: string) => void,
    _editor: IDomEditor
) => {
    const _hash = await calculateFileHash(file);
    const res = await Apis.Storage.upload({
        data: {
            dirId: 1,
            origin: "admin",
            hash: Date.now() + "",
            file
        }
    });
    const info = res.data[0];
    // 最后插入图片
    // insertFn(url, alt, href);
    if (info) insertFn(info.staticServeUrl, info.fileType, info.staticServeUrl);
};

const handleUploadVideo = async (file: File, insertFn: (url: string, poster?: string) => void, _editor: IDomEditor) => {
    const _hash = await calculateFileHash(file);
    const res = await Apis.Storage.upload({
        data: {
            dirId: 1,
            origin: "admin",
            hash: Date.now() + "",
            file
        }
    });
    const info = res.data[0];
    // 最后插入视频
    // insertFn(url, poster);
    if (info) insertFn(info.staticServeUrl, "");
};

const handleDeletedResources = async (urlsToDelete: string[]) => {
    await Apis.FileAdmin.removeBatchByUrl({
        data: { urls: urlsToDelete }
    });
};

watch(
    () => htmlStr.value,
    newValue => {
        emit("update:modelValue", newValue);
    }
);

const host = import.meta.env.VITE_API_BASE_URL;

const cleanupUnusedFile = () => {
    editRef.value?.cleanupUnusedResources(host);
};

defineExpose({
    editRef, // 编辑器实例（用于调用 API）
    cleanupUnusedFile // 清理冗余资源的公共方法
});
</script>

<style scoped lang="scss"></style>
